//
//  NetworkTools.swift
//  demoNetwork
//
//  Created by 邵禹曦 on 2019/11/19.
//  Copyright © 2019 辽宁当代. All rights reserved.
//

import UIKit
/// 导入
import AFNetworking

/// 定义枚举类型请求参数
enum RequestType : String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    /// 单例 let线程是安全的 | 闭包
    static let share: NetworkTools = {
        /// 单例
        let tools = NetworkTools()
        
        
        
        // 设置响应反序列化支持的数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        // 返回对象
        return tools
    }()
    
   
}




// MARK: - 封装请求方法
extension NetworkTools {
    
    /// request  ｜加？可选类型
    /// 新版swift协议变了，如果要传闭包需要加@escaping
    func request(methodType : RequestType, URLString : String, parameters : [String : Any] , finished : @escaping(_ retult: Any?, _ error: Error?)->()) {
        
        // 1.定义成功的回调闭包
        let successCallBack = { (task : URLSessionDataTask, result : Any?) -> Void in
            finished(result, nil)
        }
        
        // 2.定义失败的回调闭包
        let failureCallBack = { (task : URLSessionDataTask?, error : Error) -> Void in
            finished(nil, error)
        }
        

        
        // 3.发送网络请求
        if methodType == .GET {
            get(URLString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
        
        
    }
    
    
    
    

}



